package com.testitems.controller.login;

import com.testitems.common.web.result.Result;
import com.testitems.controller.login.dto.LoginRequest;
import com.testitems.controller.login.dto.LoginResponse;
import com.testitems.service.login.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

/**
 * <pre>
 *
 * </pre>
 *
 * @author GFH
 * @since 2021-11-20
 */
@Slf4j
@RestController
@RequestMapping("/api")
@Api(tags = "自定义登录接口")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    @ApiOperation(value = "登录接口", response = Result.class)
    public Result login(@RequestBody LoginRequest request) {
        try {
            final LoginResponse response = loginService.login(request);
            return Result.ok(response);
        } catch (UsernameNotFoundException notFoundException) {
            return Result.fail(notFoundException.getMessage());
        } catch (AuthenticationException authException) {
            return Result.fail("邮箱密码不匹配，请检查输入");
        }
    }

    @GetMapping("/refresh-token")
    @ApiOperation(value = "刷新token", response = Result.class)
    public Result refreshToken(@RequestHeader("${jwt.header}") String token) {
        try {
            return Result.ok(loginService.refreshToken(token));
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.fail("刷新token失败");
        }
    }

}
